﻿using System.Collections.Generic;
using System.Data.Common;
using System;
using System.Linq;
using K3R.Data;

namespace K3R.Web.Interface {
	public class LogCollection : List<Log> {
		#region Retrieval
		public static LogCollection Load(string[] codes, int? amount, int? fromId, DateTime? since) {
			ProfileCollection profiles;
			if (codes != null) {
				profiles = new ProfileCollection();
				foreach (string code in codes)
					profiles.Add(Settings.Profiles[code]);
			}
			else profiles = Settings.Profiles;

			var collection = new LogCollection();
			var amountPerProfile = (amount.HasValue ? amount.Value : 100) / profiles.Count;
			foreach (Profile profile in profiles)
				using (var conn = new Connection(profile.ConnectionString, "k3r_sqlLogging_list")) {
					conn.AddParameter("@amount", amountPerProfile);
					conn.AddParameter("@fromId", fromId);
					conn.AddParameter("@since", since);
					collection.AddRange(Convert(profile.Code, conn.ExecuteReader()));
				}

			return collection;
		}
		#endregion

		#region Conversion
		internal static LogCollection Convert(string code, DbDataReader dr) {
			var collection = new LogCollection();

			while (dr.Read())
				collection.Add(Log.Convert(code, dr));

			return collection;
		}
		#endregion
	}
}
